package per.hnvcam.searchext.controller.administration;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import per.hnvcam.searchext.Constants;
import per.hnvcam.searchext.data.model.RuleData;
import per.hnvcam.searchext.data.model.SystemConfiguration;
import per.hnvcam.searchext.services.RuleService;
import per.hnvcam.searchext.services.SpecialQuery;

@Controller("RuleController")
public class RuleController {

   private static final String RULES_GENERATION_PAGE = "administration/rules";

   @Autowired
   @Qualifier("RuleService")
   private RuleService ruleService;

   @Autowired
   @Qualifier("SpecialQuery")
   private SpecialQuery specialQuery;

   @RequestMapping(value = "/administration/rules.jhtml", method = RequestMethod.GET)
   public String showRuleSet(@RequestParam(value = "operation", required = false) String operation, Model model) {
      if (Constants.OPERATION_GENERATE_BASE_RULES.equals(operation)) {
         ruleService.removeAllBaseRules();
         ruleService.generateBaseRules();
      }
      List<RuleData> baseRules = ruleService.getAllBaseRulesData();
      model.addAttribute("baseRules", baseRules);

      if (Constants.OPERATION_GENERATE_CLASSIFY_RULES.equals(operation)) {

         model.addAttribute("initialRuleSetSize", ruleService.generateInitialRules());
         List<RuleData> flooredRuleSet = ruleService.applyFlooringToInitialRules();
         model.addAttribute("flooringRuleSetSize", flooredRuleSet.size());
         List<RuleData> classifyRuleSet = ruleService.generateClassifyRuleSet(flooredRuleSet);
         ruleService.removeAllClassifyRules();
         ruleService.persistClassifyRuleSet(classifyRuleSet);
         model.addAttribute("classifyRuleSetSize", classifyRuleSet.size());
      }

      List<RuleData> classifyRules = ruleService.getClassifyRuleSet();
      model.addAttribute("classifyRuleSet", classifyRules);

      SystemConfiguration systemConfiguration = specialQuery.getSystemConfiguration();
      model.addAttribute("classifiedClasses", systemConfiguration.getClasses());

      return RULES_GENERATION_PAGE;
   }



}
